All files / web/src/app/api/worksheets/skills/[skillId]/customize route.ts

0% Statements 0/149
0% Branches 0/1
0% Functions 0/1
0% Lines 0/149

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150                                                                                                                                                                                                                                                                                                           
import { eq, and } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { db } from '@/db'
import { skillCustomizations } from '@/db/schema'
import { getUserId } from '@/lib/viewer'
import { withAuth } from '@/lib/auth/withAuth'

/**
 * POST /api/worksheets/skills/[skillId]/customize
 *
 * Save a customization of a default skill
 */
export const POST = withAuth(async (request, { params }) => {
  try {
    const userId = await getUserId()
    const { skillId } = (await params) as { skillId: string }
    const body = await request.json()

    const { operator, digitRange, regroupingConfig, displayRules } = body

    // Validate required fields
    if (!operator || !digitRange || !regroupingConfig || !displayRules) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 })
    }

    // Validate operator
    if (operator !== 'addition' && operator !== 'subtraction') {
      return NextResponse.json({ error: 'Invalid operator' }, { status: 400 })
    }

    const now = new Date().toISOString()

    // Check if customization already exists
    const existing = await db.query.skillCustomizations.findFirst({
      where: and(
        eq(skillCustomizations.userId, userId),
        eq(skillCustomizations.skillId, skillId),
        eq(skillCustomizations.operator, operator)
      ),
    })

    if (existing) {
      // Update existing customization
      await db
        .update(skillCustomizations)
        .set({
          digitRange: JSON.stringify(digitRange),
          regroupingConfig: JSON.stringify(regroupingConfig),
          displayRules: JSON.stringify(displayRules),
          updatedAt: now,
        })
        .where(
          and(
            eq(skillCustomizations.userId, userId),
            eq(skillCustomizations.skillId, skillId),
            eq(skillCustomizations.operator, operator)
          )
        )
    } else {
      // Insert new customization
      await db.insert(skillCustomizations).values({
        userId: userId,
        skillId,
        operator,
        digitRange: JSON.stringify(digitRange),
        regroupingConfig: JSON.stringify(regroupingConfig),
        displayRules: JSON.stringify(displayRules),
        updatedAt: now,
      })
    }

    // Fetch the updated/created customization
    const customization = await db.query.skillCustomizations.findFirst({
      where: and(
        eq(skillCustomizations.userId, userId),
        eq(skillCustomizations.skillId, skillId),
        eq(skillCustomizations.operator, operator)
      ),
    })

    if (!customization) {
      return NextResponse.json({ error: 'Failed to fetch customization' }, { status: 500 })
    }

    // Return parsed customization
    return NextResponse.json({
      customization: {
        ...customization,
        digitRange: JSON.parse(customization.digitRange),
        regroupingConfig: JSON.parse(customization.regroupingConfig),
        displayRules: JSON.parse(customization.displayRules),
      },
    })
  } catch (error) {
    console.error('Failed to save skill customization:', error)
    return NextResponse.json({ error: 'Failed to save skill customization' }, { status: 500 })
  }
})

/**
 * DELETE /api/worksheets/skills/[skillId]/customize?operator=addition
 *
 * Reset a skill to its default by deleting the customization
 */
export const DELETE = withAuth(async (request, { params }) => {
  try {
    const userId = await getUserId()
    const { skillId } = (await params) as { skillId: string }
    const { searchParams } = new URL(request.url)
    const operator = searchParams.get('operator') as 'addition' | 'subtraction' | null

    if (!operator) {
      return NextResponse.json({ error: 'Operator is required' }, { status: 400 })
    }

    if (operator !== 'addition' && operator !== 'subtraction') {
      return NextResponse.json({ error: 'Invalid operator' }, { status: 400 })
    }

    // Check if customization exists
    const existing = await db.query.skillCustomizations.findFirst({
      where: and(
        eq(skillCustomizations.userId, userId),
        eq(skillCustomizations.skillId, skillId),
        eq(skillCustomizations.operator, operator)
      ),
    })

    if (!existing) {
      return NextResponse.json({ error: 'Skill customization not found' }, { status: 404 })
    }

    // Delete the customization
    await db
      .delete(skillCustomizations)
      .where(
        and(
          eq(skillCustomizations.userId, userId),
          eq(skillCustomizations.skillId, skillId),
          eq(skillCustomizations.operator, operator)
        )
      )

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Failed to delete skill customization:', error)
    return NextResponse.json({ error: 'Failed to delete skill customization' }, { status: 500 })
  }
})